/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.clinicplus.manager.search;

import br.com.foxline.clinicplus.entity.*;
import br.com.foxline.clinicplus.enums.SituationAppraisal;
import br.com.foxline.clinicplus.enums.TypeItem;
import br.com.foxline.clinicplus.enums.TypeProcedure;
import br.com.foxline.clinicplus.service.*;
import br.com.foxline.clinicplus.util.Msg;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.primefaces.context.RequestContext;
import org.primefaces.model.DualListModel;

/**
 *
 * @author roniere
 */
@ManagedBean
@ViewScoped
public class ManagerSearchTemplateAppraisal implements Serializable {

    @EJB
    TemplateAppraisalService templateAppraisalService;
    @EJB
    ProcedureService procedureService;
    @EJB
    SystemUserService systemUserService;
    @EJB
    DiaryService diaryService;
    @EJB
    AppraisalService appraisalService;
    @EJB
    CategoryService categoryService;
    @EJB
    ItemService itemService;
    private List<TemplateAppraisal> templateAppraisals;
    private TemplateAppraisal editTemplateAppraisal;
    private DualListModel<Procedure> listModel;
    private List<Category> categorys;
    private List<Category> categorysRemove;
    private String edit;
    private String show;
    private Category category;
    private Item item;
    private List<Item> items;

    @PostConstruct
    public void init() {
        templateAppraisals = templateAppraisalService.findAll();

        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        edit = params.get("templateEdit");
        show = params.get("templateShow");

        initCategory();
        params();
        proxOrdemCategoria();
    }

    private void params() {
        if (edit != null) {
            try {
                categorysRemove = new ArrayList<Category>();
                editTemplateAppraisal = templateAppraisalService.find(Long.parseLong(edit));
                List<Procedure> source = procedureService.findAll();
                List<Procedure> target = new ArrayList<Procedure>();
                if (editTemplateAppraisal != null) {
                    if (editTemplateAppraisal.getProcedures() == null) {
                        target = new ArrayList<Procedure>();
                    } else {
                        target = editTemplateAppraisal.getProcedures();
                    }
                }

                source.removeAll(target);


                categorys = categoryService.getByOrdemAsc(editTemplateAppraisal);
                //templateAppraisalService.getCategorys(editTemplateAppraisal);//.getCategorys();

                listModel = new DualListModel<Procedure>(source, target);
                category = new Category();
                item = new Item();
                items = new ArrayList<Item>();

            } catch (Exception e) {
                e.printStackTrace();
                Msg.messagemError("Modelo não encontrado");
            }
        }
    }

    public Item getItem() {
        return item;
    }

    public void setItem(Item item) {
        this.item = item;
    }

    public List<Item> getItems() {
        return items;
    }

    public void setItems(List<Item> items) {
        this.items = items;
    }

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }

    public List<Category> getCategorys() {
        return categorys;
    }

    public void setCategorys(List<Category> categorys) {
        this.categorys = categorys;
    }

    public DualListModel<Procedure> getListModel() {
        return listModel;
    }

    public void setListModel(DualListModel<Procedure> listModel) {
        this.listModel = listModel;
    }

    public TemplateAppraisal getEditTemplateAppraisal() {
        return editTemplateAppraisal;
    }

    public void setEditTemplateAppraisal(TemplateAppraisal editTemplateAppraisal) {
        this.editTemplateAppraisal = editTemplateAppraisal;
    }

    public List<TemplateAppraisal> getTemplateAppraisals() {
        return templateAppraisals;
    }

    public void setTemplateAppraisals(List<TemplateAppraisal> templateAppraisals) {
        this.templateAppraisals = templateAppraisals;
    }

    public void removerCategory(int id) {
        categorysRemove.add(categorys.get(id));
        categorys.remove(id);
    }

    public void edit() {
        try {

            for (Category cat1 : categorysRemove) {
                cat1.setStatus(false);
                categoryService.update(cat1);
            }

            editTemplateAppraisal.setUpdateAt(new Date());
            editTemplateAppraisal.setCategorys(categorys);
            editTemplateAppraisal.setSystemUserUpdate(systemUserService.getCurrentUser());
            editTemplateAppraisal.setProcedures(listModel.getTarget());
            templateAppraisalService.update(editTemplateAppraisal);
            Msg.messagemInfo("Operação realizada com Sucesso !");
            init();
        } catch (Exception e) {
            Msg.messagemInfo("Erro na Operação!");
        }

    }

    public void addItemCategory() {
        if (item.getTitulo() == null || item.getTitulo().isEmpty()) {
            Msg.messagemError("Campo 'Titulo' é obrigatório !");
            return;
        }
        if (!items.contains(item)) {
            items.add(item);
            item.setCategory(category);
        }
        item = new Item();
        proxOrdemItem();
    }

    public void proxOrdemItem() {

        if (items != null && !items.isEmpty()) {
            item.setOrdem(items.size() + 1);
        } else {
            item.setOrdem(1);
        }


    }

    public void addCategory() {

        if (category.getTitulo() == null || category.getTitulo().isEmpty()) {
            Msg.messagemError("Campo 'Nome' é obrigatório!");
            return;
        }

        category.setItems(items);

        if (!categorys.contains(category)) {
            category.setStatus(true);
            categorys.add(category);
        }
        categoryService.update(category);
        category = new Category();
        RequestContext context = RequestContext.getCurrentInstance();
        context.execute("dlgCategoryDialog.hide();");
        items = new ArrayList<Item>();
    }

    public List<SelectItem> selectTypeItem() {
        List<SelectItem> paymentTypes = new ArrayList<SelectItem>();
        for (TypeItem ms : TypeItem.values()) {
            paymentTypes.add(new SelectItem(ms, ms.getDesc()));
        }
        return paymentTypes;
    }

    public void removerItem(int id) {
        Item rem = items.get(id);
        items.remove(id);
        category.setItems(items);
        categoryService.update(category);
        itemService.delete(rem);
    }

    public void editCategory(int id) {
        category = categorys.get(id);
        items = itemService.getByOrdemAsc(category);
    }

    public void editItem(int id) {
        item = items.get(id);
//        items.remove(id);
    }

    public void initCategory() {
        category = new Category();
        items = new ArrayList<Item>();
    }

    public void proxOrdemCategoria() {

        if (categorys != null && !categorys.isEmpty() && category != null) {
            category.setOrdem(categorys.size() + 1);
        } else {
            category.setOrdem(1);
        }


    }

    public List<Item> itemsByCategory(int id) {
        List<Item> byOrdemAsc = null;
        if (categorys != null && !categorys.isEmpty()) {
            byOrdemAsc = itemService.getByOrdemAsc(categorys.get(id));
            if (byOrdemAsc != null) {
                return byOrdemAsc;
            }else if(categorys.get(id).getItems() != null && !categorys.get(id).getItems().isEmpty()) {
                return categorys.get(id).getItems();
            }
        }
        return new ArrayList<Item>();
    }
}
